package com.le.dub.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.le.dub.common.BusinessRuntimeException;
import com.le.dub.service.IFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author guole
 * @created 2024/10/9
 */
@Service
public class FileServiceImpl implements IFileService {
    @Value("${fileUrl}")
    private String fileUrl;
    @Override
    public String upload(byte[] data, String suffix, Integer type) {
        String fileName = IdUtil.simpleUUID() + "." + suffix;
        String directory=null;
        if(type==1){
            directory="clone";
        }else if(type==2){
            directory="sub";

        }
        String path=fileUrl+"/"+directory+"/"+fileName;
        try {

            File uploadFile= FileUtil.writeBytes(data, path);
            System.out.println(uploadFile);
        } catch (Exception e) {
            throw new BusinessRuntimeException("500", "上传失败" );
        }

        return "/"+directory+"/"+fileName;
    }

    @Override
    public String upload(MultipartFile file, Integer type) throws IOException {

        String[] arr = file.getOriginalFilename().split("\\." );
        String suffix = arr[arr.length - 1];
        String path =  upload(file.getBytes(), suffix, type);
        return path;
    }
}
